﻿using System;
using System.Net;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DoubanFM_Downloader
{
    public partial class MainForm : Form
    {
        JsonToDictionary jsontodictionary;
        public string apiurl = "http://douban.fm/j/mine/playlist?type=e&channel=6";
        public MainForm()
        {
            InitializeComponent();
            jsontodictionary = new JsonToDictionary();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            ArrayList musicinfo = new ArrayList();
            try
            {
                musicinfo = (ArrayList)jsontodictionary.getDictionary(apiurl)["song"];
            }
            catch (Exception ex)
            {
                MessageBox.Show("Get music list failed!!!" + ex.Message);
            }

            foreach (Dictionary<string, object> item in musicinfo)
            {
                string filename = item["title"].ToString();
                Uri fileurl = new Uri(item["url"].ToString());
                if (!System.IO.File.Exists(filename + ".mp3"))
                {
                    try
                    {
                        logTextBox.AppendText("开始下载:" + filename + "\r\n");
                        WebClient webclient = new WebClient();
                        webclient.DownloadFileAsync(fileurl, filename + ".mp3");
                        webclient.DownloadProgressChanged += webclient_DownloadProgressChanged;
                        webclient.DownloadFileCompleted += webclient_DownloadFileCompleted;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Failed and exit!" + ex.Message);
                        break;
                    }
                }
            }
        }
        #region Events
        void webclient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            Action<DownloadProgressChangedEventArgs> OnChange = ProgressChange;
            OnChange.Invoke(e);
        }

        void webclient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            //itemProgressBar.Value = 0;
            //logTextBox.AppendText(" Download success!\r\n");
        }

        void ProgressChange(DownloadProgressChangedEventArgs e)
        {
            itemProgressBar.Value = e.ProgressPercentage;
        }
        #endregion
    }
}